package com.sto.stoapp.activity.sales;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.adapter.SelectChildItemAdapter;
import com.sto.stoapp.db.manager.SelectProblemManager;
import com.sto.stoapp.entity.ProblemEntity;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.thread.BaseThread;
import com.sto.stoapp.widget.BaseActivity;

public class StoProblemSelectActivity extends BaseActivity{
	
	private ExpandableListView courierList;
	
	private List<ProblemEntity> ProblemDatas;
	
	private List<Map<String, String>> groupDatas;
	
	private List<List<Map<String, Object>>> childDatas;
	
	private SelectChildItemAdapter problemAdapter;
	
	private ProblemEntity  Entity;
	
	private int lastClick = -1;//上一次点击的group的position
	
	private boolean Flag = false; 
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.sto_problem_cause_content);
		
		groupDatas = new ArrayList<Map<String, String>>();  
	  
		childDatas = new ArrayList<List<Map<String, Object>>>();
		
		Entity = this.getIntent().getParcelableExtra("tableData");
		
		initWidget();
		initListener();
		BufferThread bufferThread = new BufferThread(this);
		bufferThread.start();
	}
	
	
	private void initWidget(){
		courierList = (ExpandableListView) findViewById(R.id.problem_causelist);
	}
	
	private void initListener(){
		
		courierList.setOnGroupClickListener(new OnGroupClickListener(){

			@Override
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) {
				
				if(lastClick == -1)  
                {  
					courierList.expandGroup(groupPosition);  
                }
				if(lastClick != -1 && lastClick != groupPosition)  
                {  
					courierList.collapseGroup(lastClick);  
					courierList.expandGroup(groupPosition);  
                }  
                else if(lastClick == groupPosition)   
                {  
                    if(courierList.isGroupExpanded(groupPosition))  
                    	courierList.collapseGroup(groupPosition);  
                    else if(!courierList.isGroupExpanded(groupPosition))  
                    	courierList.expandGroup(groupPosition);  
                }
				lastClick = groupPosition; 
				return true;
			}
			
		});
		
		courierList.setOnChildClickListener(new OnChildClickListener(){
			@Override
            public boolean onChildClick(ExpandableListView parent, View v,
                    int groupPosition, int childPosition, long id) {
				
				@SuppressWarnings("unchecked")
				Map<String, Object> data = (Map<String, Object>) problemAdapter.getChild(groupPosition, childPosition);
				Intent intent = new Intent();			
				intent.putExtra("CauseCode",data.get("child_code").toString());
				intent.putExtra("Name", data.get("child_name").toString());
				setResult(RESULT_OK, intent);
				finishEx();
                return false;
            }
				
		});
		
	}
	
	
	/**
	 * 查询数据缓冲线程
	 * 
	 * @author Administrator
	 * 
	 */
	class BufferThread extends BaseThread {
		private Context context;
		
		public BufferThread(Context context) {
			super(context);
			this.context = context;
		}

		@Override
		public void run() {
			SelectProblemManager selectTable = new SelectProblemManager(context);
			ProblemDatas = selectTable.query(Entity.getSelectSql(), Entity.getSelectField(), Entity);
			//ProblemDatas = new  ArrayList<ProblemEntity>();

			parseData(ProblemDatas);
			
			final int count = groupDatas == null ? 0 : groupDatas.size();

			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Flag = true;
					if (1 == count) {
						Intent intent = new Intent();
						intent.putExtra("Name", ProblemDatas.get(count - 1).getReasonDetail());
						intent.putExtra("CauseCode",ProblemDatas.get(count -1).getReasonCode());
						setResult(RESULT_OK, intent);
						try {
							Thread.sleep(600);

							finishEx();
						} catch (Exception e) {
							e.printStackTrace();
							ExceptionLog.writeLog("BufferThread", e.getMessage());
						}

					} else if (0 == count) {
						Intent intent = new Intent();
						setResult(RESULT_FIRST_USER, intent);
						try {
							Thread.sleep(600);
							finishEx();
						} catch (Exception e) {
							e.printStackTrace();
							ExceptionLog.writeLog("BufferThread", e.getMessage());
						}
					} else {
						problemAdapter = new SelectChildItemAdapter(  
								context, groupDatas, R.layout.sto_select_problem_group,  
				                new String[] { "courier_code",  "courier_name"},  
				                new int[] { R.id.courier_code, R.id.courier_name }, 
				                childDatas,  R.layout.sto_select_problem_list, 
				                new String[] { "child_code", "child_name" }, 
				                new int[] { R.id.child_code, R.id.child_name} ); 
						courierList.setAdapter(problemAdapter);
					}
				}
			});
		}
		
		private void parseData(List<ProblemEntity> data){
			Map<String, String> groupData = null;
			String TemKey = "";
			for(ProblemEntity entity : data){
				String key = entity.getTypeCode();
				if(("").equals(key)){
					continue;
				}
				if(!key.equals(TemKey)){
					
					splitArray(key, data);
					
					groupData = new HashMap<String, String>();
					groupData.put("courier_code", key);
					groupData.put("courier_name", entity.getTypeName());
					
					groupDatas.add(groupData);
					TemKey = key;
				}
			}
		}
		
		private void splitArray(String key, List<ProblemEntity> data){
			List<Map<String, Object>> childDataArray = null;
			
			Map<String, Object> childData = null;
			childDataArray = new ArrayList<Map<String, Object>>();
			for(ProblemEntity entity : data){
				String Value = entity.getTypeCode();
				
				if(key.equals(Value)){
					childData = new HashMap<String, Object>();
					childData.put("child_code", entity.getReasonCode());
					childData.put("child_name", entity.getReasonDetail());
					
					Log.d("Value", Value + " : " + entity.getReasonDetail());
					childDataArray.add(childData);
					
				}
				
			}
			childDatas.add(childDataArray);
		}
	}
	
	private void finishEx() {
		if(Flag){
			StoProblemSelectActivity.this.finish();
		}
	}
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if(Flag){
			super.onBackPressed();
		}
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		
		if(childDatas != null){
			childDatas.clear();
		}
		if(groupDatas != null){
			groupDatas.clear();
		}if(ProblemDatas != null){
			ProblemDatas.clear();
		}
		if(ProblemDatas != null){
			ProblemDatas.clear();
		}
		super.onDestroy();
	}
}
